﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using CustomTypeDescriptor = Jayrock.Json.Conversion.CustomTypeDescriptor;

using Jayrock.Json;
using Jayrock.Json.Conversion;
using Jayrock.Json.Conversion.Converters;

namespace N2.Jayrock.Json.Converters
{
	using ComponentModel;

	public sealed class ContentItemExporter : ExporterBase
	{
		public ContentItemExporter() : this(typeof(ContentItem)) { }

		public ContentItemExporter(Type inputType) :
			base(inputType) { }

		protected override void ExportValue(ExportContext context, object value, JsonWriter writer)
		{
			Debug.Assert(context != null);
			Debug.Assert(value != null);
			Debug.Assert(writer != null);

			var _properties = new JsonContentItemTypeDescriptor(new CustomTypeDescriptor(value.GetType())).GetProperties();

			if (_properties.Count == 0) {
				writer.WriteString(value.ToString());
			} else {
				writer.WriteStartObject();

				writer.WriteMember("__metadata");
				context.Export(new {
					type = value.GetType().AssemblyQualifiedName,
				}, writer);

				foreach (PropertyDescriptor property in _properties) {
					var _sp = property as IServiceProvider;
					var _exporter = _sp.GetService(typeof(IObjectMemberExporter)) as IObjectMemberExporter;

					if (_exporter != null) {
						_exporter.Export(context, writer, value);
					} else {
						object propertyValue = property.GetValue(value);

						if (!JsonNull.LogicallyEquals(propertyValue)) {
							writer.WriteMember(property.Name);
							context.Export(propertyValue, writer);
						}
					}
				}

				writer.WriteEndObject();
			}
		}
	}
}
